package com.hx.skyDrive.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.hx.skyDrive.biz.MyFileBiz;
import com.hx.skyDrive.entity.MyFile;
import com.hx.skyDrive.util.StringUtil;

/**
 * 文件管理类
 * @author Huathy
 * @time 2020年3月23日  下午8:41:45
 */
@RestController
@RequestMapping("/file")
public class FileController {
	
	@Autowired
	private MyFileBiz flBiz;
	
	/**
	 * 普通用户获取以核准的文件
	 * @return
	 */
	@RequestMapping("get")
	public List<MyFile> getFiles(){
		List<MyFile> list = new ArrayList<MyFile>();
		return flBiz.findAll();
	}
	
	/**
	 * 管理员查询所有文件的方法
	 * @return
	 */
	@RequestMapping("finds")
	public List<MyFile> findFiles(HttpSession session){
		Object obj = session.getAttribute("currentLoginUser");
		if(obj==null){
			return Collections.emptyList();
		}
		return flBiz.finds();
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping("myUpload")
	public List<MyFile> myUpload(String uid){
		if(uid==null || "".equals(uid)){
			return Collections.emptyList();
		}
		return flBiz.findByUid(uid);
	}
	
	@RequestMapping("pass")
	public int passFile(String fid){
		if(StringUtil.checkNull(fid)){
			return -1;
		}
		return flBiz.passFile(fid);
	}

	@RequestMapping("del")
	public int delByFid(String fid){
		if(StringUtil.checkNull(fid)){
			return -1;
		}
		return flBiz.delByFid(fid);
	}
	
	/**
	 * 文件上传方法
	 * @param fl
	 * @param req
	 * @return
	 */
	@RequestMapping("upload")
	public int upload(@RequestParam("file")MultipartFile fl, Integer uid ,HttpServletRequest req) {
		int result = -1;
		if(uid == null || uid<=0){
			return -3;	//未登录
		}
		
		if(fl.isEmpty()){
			return -2;	//请选择需要上传的文件
		}
		
		String fName = fl.getOriginalFilename().trim();
		Long size = fl.getSize();
		
		if(flBiz.isFileExist(fName,size)){
			return -4;	//文件已存在，请勿重复上传
		}
		
		try {
			String savePath = "../files";
			String path = req.getRealPath("");
			String temp = req.getServletContext().getInitParameter("filesPath");
			if( !StringUtil.checkNull(temp) ){
				savePath = temp;
			}
			
			savePath += "/" + new Date().getTime() + "-" + fName ;
			
			File dest = new File(path, savePath);
			fl.transferTo(dest);	//将文件上传到服务器

			MyFile file = new MyFile(fName,String.valueOf(size),savePath,uid);
			
			result = flBiz.add( file );
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
}
